<?php

namespace App\Containers\AppSection\Moneybox\Actions;

use App\Containers\AppSection\Moneybox\Tasks\GenerateUuidAndIdTask;
use App\Containers\AppSection\Profile\Models\Profile;
use App\Containers\AppSection\Profile\Tasks\CheckProfileAccreditationStatusTask;
use App\Containers\AppSection\User\Models\User;
use App\Containers\AppSection\User\Tasks\GetAllUsersTask;
use App\Ship\Exceptions\BadRequestException;
use App\Ship\Exceptions\InternalErrorException;
use App\Ship\Exceptions\NotFoundException;
use App\Ship\Parents\Actions\Action;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Throwable;

class BeneficiaryRegistryAction extends Action
{
    /**
     * @throws NotFoundException
     * @throws InternalErrorException
     * @throws FileNotFoundException
     * @throws BadRequestException
     */
    public function run()
    {
        $data = app(GenerateUuidAndIdTask::class)->run();
        $request = [
            'uuid' => $data['uuid'],
            'p2p_id' => $data['p2p_id'],
            'beneficiaries' => []
        ];

        // Поиск всех инвесторов
        $users = app(GetAllUsersTask::class)->with('profile')->withRole('investor')->run();

        /** @var User $user */
        foreach ($users as $user) {
            /** @var Profile $profile */
            foreach ($user->profiles as $profile) {
                $beneficiary = [];
                try {
                    // Если профиль не аккредитован
                    $accredited = app(CheckProfileAccreditationStatusTask::class)->run($profile->id, ['accreditation_accredited']);
                    if (!$accredited) {
                        throw new BadRequestException();
                    }
                } catch (Throwable $e) {
                    continue;
                }
                app(ClientDataSubAction::class)->run($beneficiary, $request['uuid'], $profile, 'beneficiary_registry', true);

                $request['beneficiaries'][] = $beneficiary;
            }
        }

        app(SendDataSubAction::class)->run($request['uuid'], config('appSection-moneybox.methods.beneficiary_registry'), $request);
    }

}
